<template>
  <div v-if="visible" class="modal-overlay" @click.self="closeModal">
    <div class="modal-container">
      <div class="modal-header">
        <h2>{{ isEdit ? '编辑课程' : '添加新课程' }}</h2>
        <button class="close-btn" @click="closeModal">&times;</button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label for="name">课程名称 *</label>
            <input
              id="name"
              v-model="formData.name"
              type="text"
              required
              placeholder="请输入课程名称"
            >
          </div>
          
          <div class="form-group">
            <label for="video">视频 URL</label>
            <input
              id="video"
              v-model="formData.video"
              type="text"
              placeholder="请输入视频 URL"
            >
          </div>
          
          <div class="form-group">
            <label for="picture">封面图片</label>
            <div class="file-upload">
              <input
                id="picture"
                ref="fileInput"
                type="file"
                accept="image/*"
                @change="handleFileUpload"
              >
              <span class="file-name">{{ pictureFileName || '选择文件...' }}</span>
              <button type="button" class="browse-btn" @click="triggerFileInput">浏览</button>
            </div>
          </div>
          
          <div class="form-group">
            <label for="content">内容</label>
            <textarea
              id="content"
              v-model="formData.content"
              rows="3"
              placeholder="请输入课程内容"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="status">状态</label>
            <select id="status" v-model="formData.status">
              <option value="active">激活</option>
              <option value="inactive">未激活</option>
              <option value="pending">待处理</option>
            </select>
          </div>
          
          <div class="form-row">
            <div class="form-group">
              <label for="extral_1">附加字段 1</label>
              <input
                id="extral_1"
                v-model="formData.extral_1"
                type="text"
                placeholder="附加字段 1"
              >
            </div>
            
            <div class="form-group">
              <label for="extral_2">附加字段 2</label>
              <input
                id="extral_2"
                v-model="formData.extral_2"
                type="text"
                placeholder="附加字段 2"
              >
            </div>
          </div>
          
          <div class="form-group">
            <label for="extral_3">附加字段 3</label>
            <input
              id="extral_3"
              v-model="formData.extral_3"
              type="text"
              placeholder="附加字段 3"
            >
          </div>
          
          <div class="form-actions">
            <button type="button" class="btn-cancel" @click="closeModal">取消</button>
            <button type="submit" class="btn-submit" :disabled="submitting">
              {{ submitting ? '保存中...' : (isEdit ? '更新' : '创建') }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, reactive } from 'vue'

const props = defineProps({
  visible: Boolean,
  courseData: Object,
  isEdit: Boolean
})

const emit = defineEmits(['update:visible', 'submit'])

// 表单数据 - 使用 ref 而不是 reactive
const formData = ref({
  name: '',
  video: '',
  picture: null,
  content: '',
  status: 'active',
  extral_1: '',
  extral_2: '',
  extral_3: ''
})

const pictureFileName = ref('')
const submitting = ref(false)
const fileInput = ref(null)

// 监听模态框显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    resetForm()
    if (props.courseData && props.isEdit) {
      loadCourseData()
    }
  }
})

// 加载课程数据（编辑时）
const loadCourseData = () => {
  Object.keys(formData.value).forEach(key => {
    if (props.courseData[key] !== undefined && props.courseData[key] !== null) {
      formData.value[key] = props.courseData[key]
    }
  })
}

// 触发文件选择
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    video: '',
    picture: null,
    content: '',
    status: 'active',
    extral_1: '',
    extral_2: '',
    extral_3: ''
  }
  pictureFileName.value = ''
  
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

// 关闭模态框
const closeModal = () => {
  emit('update:visible', false)
}

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    formData.value.picture = file
    pictureFileName.value = file.name
  }
}

// 构建FormData对象 - 修复版本
const buildFormData = () => {
  const formDataToSend = new FormData()
  
  console.log('=== 当前表单数据 ===')
  console.log(JSON.parse(JSON.stringify(formData.value)))
  
  // 手动添加每个字段，确保值不为空
  if (formData.value.name) {
    formDataToSend.append('name', formData.value.name)
  }
  if (formData.value.video) {
    formDataToSend.append('video', formData.value.video)
  }
  if (formData.value.content) {
    formDataToSend.append('content', formData.value.content)
  }
  if (formData.value.status) {
    formDataToSend.append('status', formData.value.status)
  }
  if (formData.value.extral_1) {
    formDataToSend.append('extral_1', formData.value.extral_1)
  }
  if (formData.value.extral_2) {
    formDataToSend.append('extral_2', formData.value.extral_2)
  }
  if (formData.value.extral_3) {
    formDataToSend.append('extral_3', formData.value.extral_3)
  }
  
  // 添加文件
  if (formData.value.picture instanceof File) {
    formDataToSend.append('picture', formData.value.picture)
  }
  
  return formDataToSend
}

// 提交表单
const submitForm = async () => {
  submitting.value = true
  
  try {
    // 验证必填字段
    if (!formData.value.name || !formData.value.name.trim()) {
      alert('课程名称为必填项')
      return
    }
    
    const formDataToSend = buildFormData()
    
    // 调试：打印FormData内容
    console.log('=== FormData内容 ===')
    let hasContent = false
    for (let [key, value] of formDataToSend.entries()) {
      console.log(key, value)
      hasContent = true
    }
    
    if (!hasContent) {
      console.log('FormData是空的！')
      console.log('当前formData:', formData.value)
      alert('表单数据为空，请填写表单')
      return
    }
    
    // 触发提交事件
    emit('submit', formDataToSend, props.isEdit)
    
  } catch (error) {
    console.error('表单提交错误:', error)
    alert('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  padding: 20px;
}

.modal-container {
  background: white;
  border-radius: 8px;
  width: 100%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h2 {
  margin: 0;
  color: #333;
  font-size: 1.5rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: #333;
  background-color: #f5f5f5;
  border-radius: 50%;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}

input[type="text"],
input[type="url"],
textarea,
select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

input[type="text"]:focus,
input[type="url"]:focus,
textarea:focus,
select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

textarea {
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.file-upload {
  position: relative;
  display: flex;
  align-items: stretch;
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.file-upload input[type="file"] {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.file-name {
  flex: 1;
  padding: 10px 12px;
  background: #f9f9f9;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.browse-btn {
  padding: 10px 15px;
  background: #6c757d;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.browse-btn:hover {
  background: #5a6268;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.btn-cancel {
  padding: 10px 20px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-cancel:hover {
  background: #5a6268;
}

.btn-submit {
  padding: 10px 20px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn-submit:hover:not(:disabled) {
  background: #0056b3;
}

.btn-submit:disabled {
  background: #6c757d;
  cursor: not-allowed;
  opacity: 0.7;
}

@media (max-width: 768px) {
  .modal-container {
    margin: 10px;
    width: calc(100% - 20px);
  }
  
  .form-row {
    grid-template-columns: 1fr;
  }
  
  .form-actions {
    flex-direction: column;
  }
  
  .btn-cancel,
  .btn-submit {
    width: 100%;
  }
  
  .modal-header {
    padding: 15px;
  }
  
  .modal-body {
    padding: 15px;
  }
}
</style>